<template>
  <div style="height: 100%">
    <el-dialog title="用户选择" :show-close="true" :append-to-body="propAppedToBody" :modal-append-to-body="true"
               :visible.sync="visible" :modal="true" width="60%" @open="initShow" @closed="$emit('closed')">
      <el-form ref="userQueryForm" :model="userQueryModel" label-width="100" size="mini" inline
               v-if="showUserQueryForm">
        <el-form-item label="用户编码">
          <el-input v-model="userQueryModel.code" placeholder="模糊匹配"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="userQueryModel.name" placeholder="模糊匹配"></el-input>
        </el-form-item>
        <el-form-item label="归属机构">
          <el-input v-model="userQueryModel.officeName" placeholder="模糊匹配"/>
        </el-form-item>

        <el-form-item>
          <el-button native-type="submit" type="primary" @click.submit.prevent="btnSearchClick">查询</el-button>
          <el-button @click="resetQueryForm">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="block"></div>

      <el-row style="height:100%">
        <el-col :span="20">
          <el-table ref="dataListTable" :data="userResponseModel.list" stripe border size="mini" height="35vh"
                    row-key="id" highlight-current-row @current-change="handleCurrentRowChange"
                    @selection-change="handleSelectionChange"
                    @sort-change="handleSortChange" @row-dblclick="handleRowDbClick">
            <el-table-column type="selection" :reserve-selection="true" width="50" align="center"
                             v-if="propMultiSelect"/>

            <el-table-column type="index" width="50" align="center"/>
            <el-table-column prop="code" label="用户编码" align="center" sortable/>
            <el-table-column prop="officeName" label="机构名称" align="center"/>
            <el-table-column prop="name" label="姓名" align="center"/>
            <el-table-column prop="email" label="邮箱" align="center"/>
            <el-table-column prop="lastLoginTime" label="最后登录时间" align="center" width="140"/>
            <el-table-column prop="lastLoginIp" label="最后登录IP" align="center"/>
          </el-table>
          <div class="block"></div>
          <div style="width:100%">
            <el-pagination @size-change="handlePageSizeChange" @current-change="handleCurrentPageChange"
                           :current-page="userResponseModel.currentPage" :page-sizes="[10, 20, 30, 40, 50]" :page-size="10"
                           layout="total, sizes, prev, pager, next, jumper" :total="userResponseModel.totalCount">
            </el-pagination>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="tags-box">
            <span class="title">当前已选择{{ selectedRows.length}}项</span>
            <el-tag v-for="(row,index) in selectedRows" :key="row.code" closable @close="handleTagClose(row)"
                    :disable-transitions="true">
              {{row.name}}({{row.code}})
            </el-tag>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="clearfix">
        <el-button size="mini" @click="visible = false">
          <i class="fa fa-close"></i> 取消
        </el-button>
        <el-button size="mini" @click="btnRefreshClick">
          <i class="fa fa-refresh"></i> 刷新
        </el-button>
        <el-button size="mini" @click="btnClearClick" v-if="propAllowClear">
          <i class="fa fa-eraser"></i> 清除
        </el-button>
        <el-button size="mini" type="primary" @click="btnConfirmClick">
          <i class="fa fa-check"></i> 确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'UserTableSelect',
  components: {},
  props: {
    propInitSelectedRowKeys: '',    // 初始选中行的row-key
    propRowKeysSpliter: {
      type: String,
      default: () => {
        return ','
      }
    },         // 选中行的row-key分隔符,默认以 , 隔开
    propVisible: Boolean,           // 是否可见
    propAllowClear: Boolean,        // 是否允许清空
    propMultiSelect: Boolean,       // 是否允许多选
    propAppedToBody: Boolean,        // 挡在嵌套dialog中，此属性的值需要为true，否则显示会出现问题
    propMetaData: Object,                    // 自定义元数据，在回调时传出
    propQueryModel: Object
  },

  data() {
    return {
      visible: this.propVisible,
      initSelectedRowKeys: this.propInitSelectedRowKeys,
      showUserQueryForm: true,
      userQueryModel: {
        currentPage: 1,
        rowsPerPage: 10
      },
      userResponseModel: {
        currentPage: 1,
        rowsPerPage: 10,
        totalCount: 0,
        list: []
      },
      selectedRows: []
    }
  },
  computed: {
    list() {
      return this.userResponseModel.list
    }
  },
  watch: {
    propVisible(newValue, oldValue) {
      this.visible = newValue
    },
    propInitSelectedRowKeys(newValue, oldValue) {
      this.initSelectedRowKeys = newValue
    },
    list(newValue) {
      this.initSelectedRowKeys = global.strings.defaultIfBlank(this.propInitSelectedRowKeys, '')

      if (this.propMultiSelect) {
        // this.$refs.dataListTable.clearSelection() //先清空再初始化
        let selectedRowKeys = this.initSelectedRowKeys.split(this.propRowKeysSpliter)

        newValue.forEach(o => {
          this.$refs.dataListTable.toggleRowSelection(o, false)
        })
        selectedRowKeys.forEach(o => {
          let rows = newValue.filter(p => p.code == o)
          if (rows.length > 0) {
            this.$refs.dataListTable.toggleRowSelection(rows[0], true)
          }
        })
      } else {
        this.$refs.dataListTable.setCurrentRow()
        newValue.forEach(row => {
          if (row.code == this.initSelectedRowKeys) {
            this.$refs.dataListTable.setCurrentRow(row)
          }
        })
      }
    }
  },
  methods: {
    async initShow() {
      this.selectedRows = []

      if (this.propMultiSelect) {
        this.$refs.dataListTable && this.$refs.dataListTable.clearSelection() //先清空再初始化
      }

      await this.fetchUsers()
    },
    selectRows() {

    },
    fetchUsers() {
      return new Promise((resolve, reject) => {
        Object.assign(this.userQueryModel, this.propQueryModel)

        // 具体的查询动作
        this.$ajax.get('/user/list', {
          params: this.userQueryModel
        }).then(resp => {
          this.userResponseModel.currentPage = this.userQueryModel.currentPage
          this.userResponseModel.rowsPerPage = this.userQueryModel.rowsPerPage
          this.userResponseModel.totalCount = resp.count
          this.userResponseModel.list = resp.data
          resolve(this.userResponseModel)
        })
      })
    },
    resetQueryForm() {
      this.userQueryModel = {
        currentPage: 1,
        rowsPerPage: 10
      }
    },
    btnSearchClick() {
      this.userQueryModel.currentPage = 1
      this.fetchUsers()
    },
    btnRefreshClick() {
      this.fetchUsers()
    },
    btnClearClick() {
      this.visible = false
      this.$emit('clear')
    },
    btnConfirmClick() {
      this.visible = false
      this.$emit('confirm', this.selectedRows || [], this.propMetaData)
    },
    handlePageSizeChange(val) {
      this.userQueryModel.rowsPerPage = val
      this.fetchUsers()
    },
    handleCurrentPageChange(val) {
      this.userQueryModel.currentPage = val
      this.fetchUsers()
    },
    handleCurrentRowChange(val) {
      if (this.propMultiSelect) {
        return
      }
      if (val == null) {
        return
      }
      this.selectedRows = new Array(val)
    },
    handleSelectionChange(val) {
      if (this.propMultiSelect) {
        this.selectedRows = val
      }
    },
    handleSortChange({column, prop, order}) {
      // 处理列排序
      this.userQueryModel.sidx = prop
      this.userQueryModel.order = order
      this.fetchUsers()
    },

    handleRowDbClick(row, event) {
      if (this.propMultiSelect) {
        return
      }
      this.btnConfirmClick()
    },
    handleTagClose(row) {
      this.selectedRows.splice(row, 1)

      if (this.propMultiSelect) {
        this.$refs.dataListTable.toggleRowSelection(row, false)
      } else {
        this.$refs.dataListTable.setCurrentRow()
      }
    }
  },
  created() {

  }
}
</script>
<style scoped>
</style>
